from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import time


class MD1(MiddlewareMixin):
    def process_request(self, request):
        # print(id(request))
        print('MD1 process_request')
        # return HttpResponse('MD1 process_request')

    def process_response(self, request, response):
        print('MD1 process_response')
        return response

    def process__view(self, request, view_func, view_args, view_kwargs):
        print('MD1 process__view')
        # return HttpResponse('MD1 process__view')

    def process_exception(self, request, exception):
        print('MD1 process_exception')
        return HttpResponse('异常处理好了')

    def process_template_response(self, request, response):
        print('MD1 process_template_response')
        response.template_name = 'index.html'
        return response


class MD2(MiddlewareMixin):
    def process_request(self, request):
        # print(id(request))
        print('MD2 process_request')


# 限制访问次数，实现思路
# 创建字典，ip：访问时间----循环该IP下列表的所有内容筛出，设定新的符合条件的列表----
visit_history = {

}


class Throttle(MiddlewareMixin):
    def process_request(self, request):
        # print('Throttle')
        # print(request.path_info)  # 获取路由路径
        # print(request.META.get('REMOTE_ADDR'))  # 获取用户ip地址
        ip = request.META.get('REMOTE_ADDR')
        history = visit_history.get(ip, [])  # 获取历史时间
        now = time.time()  # 获取当前时间戳
        new_history = []
        for i in history:  # 循环历史记录，筛出符合要求的时间存入新的列表
            if now - i < 5:
                new_history.append(i)

        visit_history[ip] = new_history

        if len(new_history) >= 3:  # 符合条件的数据数量大过3个就阻止
            return HttpResponse('你的手速太快了，休息一会儿')
        new_history.append(now)  # 不符合则将当前时间加入到
